<template>
  <!-- 事故调查详情弹窗 -->
  <el-dialog v-model="accidentDialog.visible" title="事故详情" draggable :with-header="false" :close-on-click-modal="false"
    size="60%" center>
    <template #header>
      <div class="flex flex-row justify-between items-center">
        <el-button type="primary" @click="handelDetailBack">关闭</el-button>
        <!-- <el-button type="success" @click="handelExhibition">{{
          accidentDialog.isExhibition ? "展示" : "取消展示"
          }}</el-button> -->
        <!-- <el-button type="danger" @click="handelExport">导出报告</el-button> -->
      </div>
    </template>
    <div>
      <div v-if="!accidentDialog.isExhibition">
        <h3 class="color-white mb-10px">事故发生成因展示</h3>
        <div class="grid grid-cols-2 gap-2 color-white">
          <div v-for="(item, index) in accidentDialog.chartsData" :key="index">
            <div>{{ item.label.slice(5, 9) }}多为</div>
            <div class="ml-10px">
              {{ item.maxData.name }}: 共{{ item.maxData.value }}起
            </div>
          </div>
        </div>
        <div v-for="(item, index) in accidentDialog.investigationData" :key="index">
          <h4>{{ item.label }}</h4>
          <div>{{ item.value }}</div>
        </div>
      </div>
      <div v-else>
        <h3 class="color-white mb-10px">调查情况</h3>
        <!-- 多行文本框 -->
        <el-input v-model="accidentDialog.investigationText" type="textarea" :autosize="{ minRows: 5, maxRows: 10 }"
          placeholder="调查情况" class="m-10px" :disabled="accidentDialog.disabled" />
        <div class="flex flex-row items-center justify-between">
          <h3 class="color-white mb-10px">治理建议</h3>
          <el-button type="success" @click="GetAiData"> AI建议</el-button>
        </div>
        <el-input v-model="accidentDialog.governanceSuggestions" type="textarea" :autosize="{ minRows: 5, maxRows: 10 }"
          placeholder="治理建议" class="m-10px" :disabled="accidentDialog.disabled" @input="handleTextareaUpdate" />
      </div>

      <h3 class="color-white mb-10px">现场照片</h3>
      <el-upload action="#" list-type="picture-card" :auto-upload="false" :on-change="handleOnPictureChange"
        :file-list="uploadedFiles" :on-remove="handleRemove" :on-success="handleSuccess"
        :on-preview="handlePictureCardPreview">
        <el-icon>
          <Plus />
        </el-icon>

        <template #file="{ file }">
          <div>
            <img class="el-upload-list__item-thumbnail" :src="file.url" alt="" />
            <span class="el-upload-list__item-actions">
              <span class="el-upload-list__item-preview" @click="handlePictureCardPreview(file)">
                <el-icon>
                  <ZoomIn />
                </el-icon>
              </span>
              <span v-if="!disabledPicture" class="el-upload-list__item-delete" @click="handleRemove(file)">
                <el-icon>
                  <Delete />
                </el-icon>
              </span>
            </span>
          </div>
        </template>
      </el-upload>

      <el-dialog v-model="pictureVisible">
        <img w-full :src="dialogImageUrl" alt="Preview Image" />
      </el-dialog>

      <div class="mt-10px flex justify-center">
        <el-button type="primary" @click="handelSave">保存</el-button>
        <el-button :disabled="accidentDialog.disabledExport" type="danger" @click="handelExport">导出报告</el-button>
      </div>
    </div>
  </el-dialog>
  <div class="text-#fff absolute right-20% top-20px flex items-center" v-show="accidentDialog.showBtn">
    <div class="sgdc-icon w-80px h-32px px-8px box-border flex items-center justify-center z-3"
      @click="booleanStore.setFixedRoute(true)">
      漫游
    </div>
    <div class="sgdc-icon w-100px h-32px px-8px box-border flex items-center justify-center z-3 mx-10px"
      @click.stop="accidentDialog.visible = !accidentDialog.visible">
      事故调查
    </div>
  </div>
</template>

<script setup lang="ts">
// import { PIE_CHART_ITEM } from "@/const/home";
import { useBoolean } from "@/store";
import * as MapApi from "@/service/api/map";
import { PostReport, GetReport,
  // GetPieChartsDatas
} from "@/service/api/SamplInterface";
import type { UploadFile, UploadFiles } from "element-plus";
interface Props {
  modelValue: boolean;
  statisticDialog: any; // 接收父组件传递的 statisticDialog
  timeData: any; // 接收父组件传递的 timeData
}

const message = useMessage();
const booleanStore = useBoolean();
const props = defineProps<Props>();
const emit = defineEmits(["back"]);
//事故调查详情弹窗
const accidentDialog = reactive<any>({
  visible: false,
  showBtn: false,
  isExhibition: true,
  chartsData: [], //图形数据
  investigationData: [], //调查情况数据
  investigationText: "热点路段周边有大型载货汽车密集停放，说明大货车在该路段密集通行，热点路段为连续弯道路段，弯道曲率接近90°。", //调查情况文本框的内容
  governanceSuggestions: "一是在北侧长距离直行道路处加设限速标识以及超速抓拍设备，二是在弯道和岔道前设立急弯和岔道标识，并加装减速带；三是在弯道处加装凸面镜扩大视野范围。", //治理建议文本框的内容
  disabledExport: true, //控制导出按钮
  reportId: "", //报告id
});

const uploadedFiles = ref<UploadFile[]>([]);
const disabledPicture = ref(false);
const pictureVisible = ref(false);
const dialogImageUrl = ref("");
const currentDetail = ref<any>({});
const fileList = ref<UploadFile[]>([]);

watch(
  () => props.modelValue,
  (newVal) => {
    accidentDialog.showBtn = newVal;
  }
);

watch(() => booleanStore.fixedRouteShow, (newVal) => {
  accidentDialog.visible = !newVal;
  accidentDialog.showBtn = !newVal;
})

const handelDetailBack = () => {
  accidentDialog.visible = false;
  const { draw, primitiveLoader, map3d } = window.cesiumInit;
  map3d.camera.zoomOut(200);
  draw.drawLayer && (draw.drawLayer.show = true);
  if (primitiveLoader.heatLayer.length > 0) {
    primitiveLoader.heatLayer.forEach((item) => {
      item.show = true;
    });
  }
  primitiveLoader.deleteClusterGraphic();
  emit("back");
};

// const handelFixedRoute = () => {
//   booleanStore.setFixedRoute(true);
// };

// const handelOperateGLTF = async() =>{
//   const { draw } = window.cesiumInit;
//   gltfShow.value = await draw.handelOperateGLTF();
// }

// const handelExhibition = async () => {
//   if (!accidentDialog.chartsData) {
//     accidentDialog.isExhibition = !accidentDialog.isExhibition;
//     return;
//   }
//   const ids = props.statisticDialog.data;
//   const exportDataPromises = PIE_CHART_ITEM.map((item) => {
//     return generateData(item.type, ids).then((data) => {
//       // 找到最大值
//       const maxValueItem = data.reduce((max, current) => {
//         return current.value > max.value ? current : max;
//       }, data[0]);

//       return {
//         label: item.label,
//         maxData: maxValueItem, // 只保留最大值
//       };
//     });
//   });
//   // 等待所有 Promise 完成
//   const exportData = await Promise.all(exportDataPromises);
//   accidentDialog.investigationData = [];
//   if (accidentDialog.investigationText) {
//     accidentDialog.investigationData.push({
//       label: "调查结果",
//       value: accidentDialog.investigationText,
//     });
//   }
//   if (accidentDialog.governanceSuggestions) {
//     accidentDialog.investigationData.push({
//       label: "治理建议",
//       value: accidentDialog.governanceSuggestions,
//     });
//   }
//   accidentDialog.chartsData = exportData;
//   accidentDialog.isExhibition = !accidentDialog.isExhibition;
// };

const handelSave = async()=>{
  try {
    const data = {
      sgbhList: props.statisticDialog.data,
      startTime: props.timeData.startTime,
      endTime: props.timeData.endTime,
      reportContent: accidentDialog.investigationText,
      reportSuggestion: accidentDialog.governanceSuggestions,
      images: fileList.value,
    };
    const res = await PostReport(data);

    if (res?.reportId) {
      message.success("保存成功");
      accidentDialog.disabledExport = false;
      accidentDialog.reportId = res.reportId;
    }
  } catch (err) {
    console.log(err);
  }
}

const handelExport = async () => {
  try {
    await GetReport(accidentDialog.reportId);
  } catch (err) {
    console.log(err);
  }
};

const GetAiData = async () => {
  try {
    const chat_id = "1f785cc6ff2211efbb310242ac120002";
    const api_key = "ragflow-c3NDc3MjAwMDllNzExZjA4MjE5MDI0Mm";
    const url = `http://65.72.0.10/api/v1/chats_openai/${chat_id}/chat/completions`;

    const response = await fetch(url, {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
        Authorization: `Bearer ${api_key}`,
      },
      body: JSON.stringify({
        model: "deepseel-r:70b",
        messages: [{ role: "user", content: accidentDialog.investigationText }],
        stream: true,
      }),
    });

    if (response.body) {
      const reader = response.body.getReader();
      let result = "";

      let buffer = "";

      while (true) {
        const { done, value } = await reader.read();
        if (done) break;
        buffer += new TextDecoder().decode(value);
      }

      const lines = buffer.split("\n");
      for (const line of lines) {
        if (!line.trim()) continue;
        try {
          if (line.startsWith("data:")) {
            const dataStr = line.slice(5);
            if (dataStr === "[DONE]") {
              continue;
            }
            const data = JSON.parse(dataStr);
            const content = data.choices?.[0]?.delta?.content;
            if (content) {
              result += content;
            }
          } else {
            const data = JSON.parse(line);
            const content = data.choices?.[0]?.delta?.content;
            if (content) {
              result += content;
            }
          }

          processAIMessage(result);
        } catch (err) {
          console.error("解析失败:", err);
        }
      }
    }
  } catch (err) {
    console.error("请求失败:", err);
  }
};

const processAIMessage = (data: string) => {
  if (!hasThinkTag(data)) return;
  const thinkContent = getThinkContent(data);
  const regularContent = getRegularContent(data);
  const fillContent = (type: "think" | "content", text: string) => {
    let index = 0;
    const writer = () => {
      if (index < text.length) {
        accidentDialog.governanceSuggestions += text[index];
        index++;
        setTimeout(writer, 50);
      } else if (type === "think") {
        accidentDialog.governanceSuggestions += "\n";
        fillContent("content", regularContent);
      }
    };
    writer();
  };
  fillContent("think", thinkContent);
};
const hasThinkTag = (content: string) => {
  return /<think>[\s\S]*<\/think>/.test(content);
};
const getThinkContent = (content: string) => {
  const match = content.match(/<think>([\s\S]*)<\/think>/);
  return match ? match[1] : "";
};
const getRegularContent = (content: string) => {
  return content.replace(/<think>[\s\S]*<\/think>/g, "").trim();
};

const handleTextareaUpdate = () => {
  nextTick(() => {
    const textarea = document.querySelector(".fixed-textarea textarea");
    if (textarea) {
      textarea.scrollTop = textarea.scrollHeight;
    }
  });
};

const handleOnPictureChange = async (
  file: UploadFile,
  uploadFiles: UploadFiles
) => {
  uploadedFiles.value = uploadFiles;

  if (file.status === "success" || file.status === "fail") {
    return;
  }

  const loading = message.loading("图片上传中...");

  try {
    if (!file.raw) {
      throw new Error("文件无效");
    }

    const formData = new FormData();
    formData.append("file", file.raw, file.name);

    if (currentDetail.value?.id) {
      formData.append("accidentId", currentDetail.value.id.toString());
    }

    const res = await MapApi.PostAccidentHeatpictur(formData);

    if (!res || !res.wholeUrl) {
      throw new Error(res?.msg || "上传失败，服务器未返回有效图片地址");
      return;
    }
    const uploadedFileItem = uploadedFiles.value.find(
      (item) => item.uid === file.uid
    );
    if (uploadedFileItem) {
      uploadedFileItem.status = "success";
      uploadedFileItem.url = res.wholeUrl;
      uploadedFileItem.response = res;
    } else {
      console.warn("上传成功后未找到对应文件项，这可能导致显示问题。");
      file.url = res.wholeUrl;
      file.status = "success";
    }
    fileList.value.push(res);
    message.success("图片上传成功");
  } catch (err: any) {
    console.error("上传错误:", err);
    const uploadedFileItem = uploadedFiles.value.find(
      (item) => item.uid === file.uid
    );
    if (uploadedFileItem) {
      uploadedFileItem.status = "fail";
    } else {
      file.status = "fail";
    }
    message.error(err.message || "图片上传失败");
  } finally {
    loading.close();
  }
};

const handleSuccess = (response: any, uploadFile: UploadFile) => {
  const uploadedFileItem = uploadedFiles.value.find(
    (item) => item.uid === uploadFile.uid
  );
  if (uploadedFileItem) {
    uploadedFileItem.url = response.url || response.wholeUrl;
    uploadedFileItem.status = "success";
  }
  message.success("图片上传成功");
};

const handleRemove = async (file: UploadFile) => {
  const indexToDelete = uploadedFiles.value.findIndex(
    (item) => item.uid === file.uid
  );

  if (indexToDelete !== -1) {
    // 从 uploadedFiles.value 中移除文件，并更新响应式数据
    const newUploadedFiles = uploadedFiles.value.filter(
      (item) => item.uid !== file.uid
    );
    uploadedFiles.value = newUploadedFiles;
    fileList.value.splice(indexToDelete, 1);

    message.info("图片已从列表中移除");
  } else {
    console.warn("未能在 uploadedFiles.value 中找到要删除的文件:", file);
    message.warning("未能找到要删除的图片，请检查。");
  }
};

const handlePictureCardPreview = (file: UploadFile) => {
  if (file.url) {
    dialogImageUrl.value = file.url;
    pictureVisible.value = true;
  }
};

// const generateData = async (type: string, ids: []) => {
//   try {
//     const res = await GetPieChartsDatas(type, ids);

//     // 检查数据是否为空
//     if (!res || res.length === 0) {
//       return [{ name: "无数据", value: 0 }];
//     }
//     return res;
//   } catch (err) {
//     console.error("获取数据失败:", err);
//     return [{ name: "无数据", value: 0 }]; // 返回默认数据
//   }
// };

onUnmounted(() => {
  booleanStore.fixedRouteShow=false;
  accidentDialog.showBtn = false;
})
</script>

<style lang="less" scoped>
@import "@/style/elementPlus.less";

.sgdc-icon {
  background: url("@/assets/img/analysis/bg-3.png") center/cover no-repeat;
  background-size: 100% 100%;
}
</style>
